// Page Initialization
$(document).ready(() => {
    loadSearchHistory();   // Load search history
    renderPopularFoods();  // Render popular foods
});

// Search button click/Enter key trigger
$('#searchBtn').click(handleSearch);
$('#searchInput').keypress((e) => {
    if (e.key === 'Enter') handleSearch();
});

// Handle search logic
function handleSearch() {
    const foodName = $('#searchInput').val().trim();
    if (!foodName) {
        alert('Please enter a food name');
        return;
    }

    // Simulate calorie lookup
    const calorie = getFoodCalorie(foodName);
    if (calorie === 0) {
        alert('No calorie data found for this food');
        return;
    }

    // Save search history and refresh display
    saveSearchHistory(foodName, calorie);
    $('#searchInput').val('');  // Clear input field
    loadSearchHistory();       // Reload search history
}

// Save search history to localStorage
function saveSearchHistory(foodName, calorie) {
    const history = JSON.parse(localStorage.getItem('searchHistory')) || [];
    const newHistory = [
        { name: foodName, calorie, time: new Date().getTime() },
        ...history.filter(item => item.name !== foodName)
    ].slice(0, 5); // Keep last 5 records
    localStorage.setItem('searchHistory', JSON.stringify(newHistory));
}

// Load and render search history (sync with post.html records)
function loadSearchHistory() {
    const history = JSON.parse(localStorage.getItem('searchHistory')) || [];
    const $historyList = $('#historyList');
    $historyList.empty();

    // Sync total calories with post.html records
    const dailyRecords = JSON.parse(localStorage.getItem('dailyRecords')) || [];
    const today = new Date().toDateString();
    const todayRecords = dailyRecords.filter(rec => 
        new Date(rec.date).toDateString() === today
    );
    const totalCalorie = todayRecords.reduce((sum, rec) => sum + rec.calories, 0);
    $('#totalCalorie').text(totalCalorie);

    // Render history items with "Add to Record" button
    history.forEach(item => {
        const time = new Date(item.time).toLocaleString('en-US');
        $historyList.append(`
            <div class="history-item">
                <div>
                    <p class="mb-1">${item.name}</p>
                    <span class="history-time text-muted">${time}</span>
                </div>
                <div class="fw-bold">${item.calorie} kcal</div>
                <button class="btn btn-sm btn-success ms-3" 
                        onclick="addToDailyRecord('${item.name}', ${item.calorie})">
                    Add to Daily Record
                </button>
            </div>
        `);
    });
}

// Render popular foods (dynamic sync with post.html)
function renderPopularFoods() {
    const popularFoods = [
        { name: 'Apple', calorie: 52 },
        { name: 'Banana', calorie: 89 },
        { name: 'Beef', calorie: 250 },
        { name: 'Chicken Breast', calorie: 165 },
        { name: 'Egg', calorie: 70 },
        { name: 'Milk', calorie: 60 }
    ];

    const $popularList = $('#popularList');
    popularFoods.forEach(food => {
        $popularList.append(`
            <div class="popular-item" onclick="autoFillSearch('${food.name}')">
                <p class="mb-1">${food.name}</p>
                <small class="text-muted">${food.calorie} kcal/100g</small>
            </div>
        `);
    });
}

// Auto-fill search input
window.autoFillSearch = (foodName) => {
    $('#searchInput').val(foodName);
    handleSearch();
}

// Add to daily record (pass data to post.html)
window.addToDailyRecord = (foodName, calorie) => {
    const prefillData = {
        food: foodName,
        calories: calorie,
        details: `${foodName} (from calorie search)`
    };
    sessionStorage.setItem('postPrefill', JSON.stringify(prefillData));
    window.location.href = 'post.html';
}

// Simulated calorie lookup
function getFoodCalorie(foodName) {
    const calorieMap = {
        'Apple': 52, 
        'Banana': 89, 
        'Beef': 250,
        'Chicken Breast': 165, 
        'Egg': 70, 
        'Milk': 60
    };
    return calorieMap[foodName] || 0;
}
function logout() {
    // Remove the logged-in user's information from local storage
    localStorage.removeItem("loggedinUser");
}